package com.zpp.friend.service.exam.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zpp.common.core.constants.Constants;
import com.zpp.common.core.domain.TableDataInfo;
import com.zpp.common.core.utils.ThreadLocalUtil;
import com.zpp.friend.domain.exam.dto.ExamQueryDTO;
import com.zpp.friend.domain.exam.vo.ExamVO;
import com.zpp.friend.manager.ExamCacheManager;
import com.zpp.friend.mapper.exam.ExamMapper;
import com.zpp.friend.service.exam.IExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ExamServiceImpl implements IExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Override
    public List<ExamVO> list(ExamQueryDTO examQueryDTO) {
        //设置分页
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());

        return examMapper.selectExamList(examQueryDTO);
    }

    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {
        //从redis当中获取竞赛列表数据
        Long total = examCacheManager.getListSize(examQueryDTO.getType(), null);
        List<ExamVO> examVOList;
        if(total == null || total <= 0) {
            examVOList = list(examQueryDTO);
            examCacheManager.refreshCache(examQueryDTO.getType(),null);
            total = new PageInfo<>(examVOList).getTotal();
        }else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO,null);
            total = examCacheManager.getListSize(examQueryDTO.getType(), null);
        }

        if(CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }

        //标记当前用户已经报名的竞赛
        assembleExamVOList(examVOList);

        //获取符合条件查询的总数
        return TableDataInfo.success(examVOList, total);

    }

    private void assembleExamVOList(List<ExamVO> examVOList) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        List<Long> userExamIdList= examCacheManager.getAllUserExamList(userId);
        if(CollectionUtil.isEmpty(userExamIdList)) {
            return;
        }
        for(ExamVO examVO : examVOList) {
            if(userExamIdList.contains(examVO.getExamId())) {
                examVO.setEnter(true);
            }
        }
    }
}
